package com.example.yiqinmanagersystem.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yiqinmanagersystem.entity.Menu;
import com.example.yiqinmanagersystem.entity.User;
import com.example.yiqinmanagersystem.service.MenuService;
import com.example.yiqinmanagersystem.service.RoleService;
import com.example.yiqinmanagersystem.utils.TreeNode;
import com.example.yiqinmanagersystem.utils.TreeNodeBuilder;
import com.example.yiqinmanagersystem.vo.MenuVo;
import com.example.yiqinmanagersystem.vo.ResponseCode;
import com.example.yiqinmanagersystem.vo.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/*
 **@Author:youpeng
 **Created on 2022/9/14
 */
@RestController
@RequestMapping("/api")
public class MenuController {

    @Resource
    private MenuService menuService;

    @Resource
    private RoleService roleService;

    /*
    * 获取菜单列表
    * */
    @GetMapping("/menu/loadAllMenu")
    public ResponseResult loadAllMenu(MenuVo menuVo){
        //1.创建分页对象,限制大小
        Page<Menu> page = new Page<>(menuVo.getPage(),menuVo.getLimit());
        //2.创建条件
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNoneBlank(menuVo.getTitle()),"title",menuVo.getTitle());
        queryWrapper.orderByAsc("ordernum");
        Page<Menu> menuPage = menuService.page(page, queryWrapper);
        if(menuPage.getSize()!=0){
            return new ResponseResult(ResponseCode.SUCCESS, Math.toIntExact(page.getTotal()),page.getRecords());
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 加载初始化下拉菜单
    * */
    @GetMapping("/menu/loadMenuManagerLeftTreeJson")
    public ResponseResult loadMenuManagerLeftTreeJson(){
        List<Menu> list = menuService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu menu : list) {
            Boolean open = menu.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(menu.getId(),menu.getPid(),menu.getTitle(),open));
        }
        if(list.size()>0){
            return new ResponseResult(ResponseCode.SUCCESS,treeNodes);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 赋值最大的排序码 +1
    * */
    @GetMapping("/menu/loadMenuMaxOrderNum")
    public ResponseResult loadMenuMaxOrderNum(){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        IPage<Menu> page = new Page<>(1,1);
        List<Menu> list = menuService.page(page, queryWrapper).getRecords();
        map.put("value",list.get(0).getOrdernum()+1);
        if(list.size()>0){
            return new ResponseResult(ResponseCode.SUCCESS,map);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 新增菜单
    * */
    @PostMapping("/menu/addMenu")
    public ResponseResult addMenu(Menu menu){
        menu.setType("menu");
        boolean b = menuService.save(menu);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 修改菜单
    * */
    @PostMapping("/menu/updateMenu")
    public ResponseResult updateMenu(Menu menu){
        boolean b = menuService.updateById(menu);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 判断是否有子菜单
    * */
    @PostMapping("/menu/checkMenuHasChildrenNode")
    public ResponseResult checkMenuHasChildrenNode(Menu menu){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",menu.getId());
        List<Menu> list = menuService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",true);
            return new ResponseResult(ResponseCode.FAILED);
        }else {
            map.put("value",false);
            return new ResponseResult(ResponseCode.SUCCESS);
        }
    }

    /*
    * 删除菜单
    * */
    @PostMapping("/menu/deleteMenu")
    public ResponseResult deleteMenu(Menu menu){
        boolean b = menuService.removeById(menu.getId());
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    *加载主页面index的菜单栏，带有层级关系
    * 【不同用户不同菜单】
    * */
    @GetMapping("/menu/loadIndexLeftMenuJson")
    public ResponseResult loadIndexLeftMenuJson(Menu menu1, HttpSession session){
        //查询所有菜单
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        List<Menu> list = null;
        //1.按条件查询 【管理员、其他、学生、老师】
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();
        if (user.getUsername().equals("admin") || StringUtils.equals(user.getUsername(), "admin")) {
            list = menuService.list();
        }else {
            //2.根据用户id 查询角色id
            List<Integer> currentUserRoleIds = roleService.queryUserRoleById(userId);
            //3.根据角色id 查询菜单 id 去重
            Set<Integer> mids = new HashSet<>();
            for (Integer rid : currentUserRoleIds) {
                //3.1 根据角色id 查询菜单 id
                List<Integer> permissionIds = roleService.queryAllPermissionByRid(rid);
                //3.2 角色id 和 菜单id 去重
                mids.addAll(permissionIds);
            }
            //4.根据角色id 查询菜单
            if(mids.size()>0){
                queryWrapper.in("id",mids);
                list = menuService.list(queryWrapper);
            }
        }
        //层级关系
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Menu menu : list) {
            Integer id = menu.getId();
            Integer pid = menu.getPid();
            String title = menu.getTitle();
            String icon = menu.getIcon();
            String href = menu.getHref();
            Boolean open = menu.getOpen().equals(1)?true:false;
            treeNodes.add(new TreeNode(id,pid,title,icon,href,open));
        }
        //层级关系
        List<TreeNode> nodeList = TreeNodeBuilder.build(treeNodes, 0);
        if(nodeList!=null){
            return new ResponseResult(ResponseCode.SUCCESS,nodeList);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }
}
